<template>
  <div class="h-full flex flex-col">
    <!-- 顶部标题 -->
    <div class="p-4 border-b border-gray-200">
      <h2 class="text-lg font-medium">新的朋友</h2>
    </div>

    <!-- 好友请求列表 -->
    <div class="flex-1 overflow-y-auto p-4">
      <div v-if="friendRequests.length > 0">
        <div v-for="request in friendRequests" :key="request.id"
          class="flex items-center p-4 mb-4 bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow">
          <el-avatar :size="48" :src="request.avatar" />
          <div class="ml-4 flex-1">
            <div class="font-medium">{{ request.nickname }}</div>
            <div class="text-sm text-gray-500">{{ request.remark || '请求添加你为好友' }}</div>
          </div>
          <div class="flex gap-2" v-if="request.status === 0">
            <el-button type="primary" size="small" @click="handleAccept(request)" :loading="request.loading">
              接受
            </el-button>
            <el-button type="default" size="small" @click="handleReject(request)" :loading="request.loading">
              拒绝
            </el-button>
          </div>
          <div v-else class="text-gray-500 text-sm">
            <span v-if="request.status === 1">已接受</span>
            <span v-else-if="request.status === 2">已拒绝</span>
            <span v-else-if="request.status === 3">已拉黑</span>
          </div>
        </div>
      </div>
      <div v-else class="flex flex-col items-center justify-center h-full text-gray-500">
        <el-icon :size="48" class="mb-4">
          <UserFilled />
        </el-icon>
        <p>暂无新的好友请求</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { handleFriendRequest } from '@/api/contact'
import type { FriendRequestData } from '@/types'
import { useContactStore } from '@/stores/useContactStore'

interface FriendRequestWithLoading extends FriendRequestData {
  loading?: boolean
}

const contactStore = useContactStore()
const friendRequests = computed(() => contactStore.friendRequests)

// 处理接受好友请求
const handleAccept = async (request: FriendRequestWithLoading) => {
  request.loading = true
  try {
    await handleFriendRequest(request.id, 1)  // 使用数字1表示接受
    contactStore.updateRequestStatus(request.id, 1)
    ElMessage.success('已接受好友请求')
  } catch (error: any) {
    ElMessage.error(error.message || '处理好友请求失败')
  } finally {
    request.loading = false
  }
}

// 处理拒绝好友请求
const handleReject = async (request: FriendRequestWithLoading) => {
  request.loading = true
  try {
    await handleFriendRequest(request.id, 2)  // 使用数字2表示拒绝
    contactStore.updateRequestStatus(request.id, 2)
    ElMessage.success('已拒绝好友请求')
  } catch (error: any) {
    ElMessage.error(error.message || '处理好友请求失败')
  } finally {
    request.loading = false
  }
}

onMounted(() => {
  // 获取好友请求列表
  contactStore.fetchFriendRequests()
})
</script>